<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="小说名" prop="userName">
            <el-input
              v-model="queryParams.bookName"
              placeholder="请输入小说名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="作者" prop="phonenumber">
            <el-input
              v-model="queryParams.authorName"
              placeholder="请输入作者昵称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="bookStatus">
            <el-select
              v-model="queryParams.status"
              placeholder="小说状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dicts"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

<!--        <el-row :gutter="10" class="mb8">-->
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="primary"-->
<!--              plain-->
<!--              icon="el-icon-plus"-->
<!--              size="mini"-->
<!--              @click="handleAdd"-->
<!--              v-hasPermi="['system:user:add']"-->
<!--            >新增</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="danger"-->
<!--              plain-->
<!--              icon="el-icon-delete"-->
<!--              size="mini"-->
<!--              :disabled="this.ids.length>0"-->
<!--              @click="handleDelete"-->
<!--              v-hasPermi="['system:user:remove']"-->
<!--            >删除</el-button>-->
<!--          </el-col>-->
<!--          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" ></right-toolbar>-->
<!--        </el-row>-->

        <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="小说编号" align="center" type="index" :index="indexMethod"  />
          <el-table-column label="小说名" align="center" key="bookName" prop="bookName"  :show-overflow-tooltip="true" />
          <el-table-column label="小说分类" align="center" key="catName" prop="catName" :show-overflow-tooltip="true"/>
          <el-table-column label="作者" align="center" key="authorName" prop="authorName"   :show-overflow-tooltip="true" />
          <el-table-column label="完结情况" align="center" key="bookStatus" prop="bookStatus" :formatter="formatter" width="120" />
          <el-table-column label="字数" align="center" key="wordCount" prop="wordCount" width="120" />
          <el-table-column label="状态" align="center" key="status" >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="true"
                :inactive-value="false"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="最新章节" align="center" prop="lastIndexName"  width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.lastIndexName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              >删除</el-button>
              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="readNovelIndex" icon="el-icon-key"
                                    v-hasPermi="['sys:user:resetPwd']">查看目录</el-dropdown-item>
                  <el-dropdown-item command="addNovelCategory" icon="el-icon-circle-check"
                                    v-hasPermi="['sys:novel:add']">添加分类</el-dropdown-item>
                  <el-dropdown-item command="indexManage" >
                    小说章节管理
                  </el-dropdown-item>
                  <el-dropdown-item command="readDesc">查看简介</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <el-dialog  :title="title" :visible.sync="dialogVisible" v-if="dialogVisible">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-row >
          <el-col :span="12">
            <el-form-item label="小说名">
              <el-input v-model="form.bookName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者">
              <el-input v-model="form.authorName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="最新章节">
              <el-input v-model="form.lastIndexName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="小说种类">
              <el-radio-group v-model="form.workDirection">
                <el-radio v-for="direction in directions" :label="direction.value" >{{direction.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="小说简介">
            <el-input type="textarea" :autosize="{minRows: 1,maxRows: 5}" v-model="form.bookDesc"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
            <el-form-item label="小说分类">
              <el-select v-model="form.catId" placeholder="请选择">
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
        </el-row>
        <!--TODO 上传封面的图片-->
      </el-form>
      <div slot="footer" >
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="小说章节" :visible.sync="indexVisiable">
      <h2>共{{indexList.length}}章  最后章节：{{indexList.length>0?indexList[indexList.length-1].indexName:'该小说暂无更新章节'}}</h2>
      <el-row gutter="20">
        <el-col :span="8" v-for="(novelIndex,index) in indexList" style="margin-bottom: 10px">
          <i style="font-style: normal" class="text-hidden">{{novelIndex.indexName}}</i>
        </el-col>
      </el-row>
    </el-dialog>


    <el-dialog title="简介" :visible.sync="descVisible" v-if="descVisible" width="30%">
      <el-input
        type="textarea"
        disabled
        v-model="currentDesc"
        :autosize="{minRows:2,maxRows:10}"></el-input>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {bookList, deleteById, getBookById, readNovelIndex,updateBook,changeBookStatus} from "@/api/sys/novel";
import {categoryList} from "@/api/sys/category";
import UpLoad from "@/components/UpLoad/index"
import router from "@/router";

const dicts=[{dictLabel:"正常",dictValue:"0",status:"0",default:true},{dictLabel:"停用",dictValue:"1",status:"0",default:false}]
export default {
  name: "novel",
  components: {
    UpLoad
  },

  data() {
    return {
      dicts:{...dicts},
      // 遮罩层
      loading: true,

      indexVisiable: false,
      // 选中数组
      ids: [],
      directions:[
        {label:'男频',value:false},
        {label:'女频',value: true}
      ],

      currentDesc:'',

      descVisible:false,

      dialogVisible:false,

      categoryList:[],

      indexList:[],
      //选中的小说名
      bookNames:'',
      // 非单个禁用
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      bookList: null,
      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bookName: undefined,
        authorName: undefined,
        bookStatus: undefined,
      },
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      bookList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.bookList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    //获取所有的分类
    getCategoryList(){
      categoryList(undefined).then(response=>{
        this.categoryList = response.data.records

      })
    },
    /** 获取当前索引*/
    indexMethod(index){
      return index+1
    },
    //格式化性别数据
    formatter(row,column){
      if (row.bookStatus){
        return '完结'
      }else {
        return '连载中'
      }

    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status ? "启用" : "停用";
      this.$confirm(`确认要${text}${row.bookName}吗？`).then(function() {
        return changeBookStatus(row.id, row.status);
      }).then(() => {
        this.$message.success(text+"成功")
        //this.$Modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status ? false : true;
      });
    },
    //跳转到章节管理页面
    indexManage(row){
      this.$router.push({path:`/sys/book-index/${row.id}`})
    },
    readDesc(row){
      //弹出消息框
      this.descVisible=true
      this.currentDesc = row.bookDesc
    },
    // 取消按钮
    cancel() {
      this.dialogVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.bookNames=''
      selection.filter(item=>{
        if (this.bookNames){
          this.bookNames=`${this.bookNames},`
        }
        this.bookNames=`${this.bookNames}${item.name}`
      })
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "readNovelIndex":
          this.readNovelIndex(row);
          break;
        case "addNovelCategory":
          //this.handleAuthRole(row);
          this.addNovelCategory(row)
          break;
        case "indexManage":
          this.indexManage(row)
          break;
        case "readDesc":
          this.readDesc(row)
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      //跳转到爬取小说页面
      router.push("/sys/crawl")
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const bookId = row.id || this.ids;

      getBookById(bookId).then(response => {
        this.form = response.data;
        this.dialogVisible=true
        this.title = "修改小说";
        //查询小说分类
        this.getCategoryList()

      });
    },
    /** 重置密码按钮操作 */
    readNovelIndex(row) {
      //查看该小说的章节信息
      var formData = new FormData()
      formData.append("bookId",row.id)
      readNovelIndex(formData).then(response=>{
        this.indexList = response.data
        this.indexVisiable=true
      })
    },
    /** 阅读过的小说列表 */
    addNovelCategory: function(row) {
      const id = row.id;
      this.$router.push("/sys/book-category/category/" + id);
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          for (let key in this.form){
            if (this.form[key]==null){
              this.form[key]=undefined
            }
          }
          if (this.form. id!= undefined) {
            updateBook(this.form).then(response => {
              this.$message.success("修改成功");
              this.cancel()
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bookIds = row.id || this.ids;
      this.$confirm(`是否确认删除小说名为【${row.bookName?row.bookName:this.bookNames}】的数据项？`).then(function() {
        return deleteById(bookIds);
      }).then(() => {
        this.getList();

        this.$message.success("删除成功");
      }).catch(() => {});
    },
  }
};
</script>
